package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.apis.comment.ICommentClient;
import com.heima.model.comment.dtos.ALLCommentListDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.CommentListDto;
import com.heima.model.comment.dtos.CommentRepaySaveDto;
import com.heima.model.comment.pojos.*;
import com.heima.model.comment.vos.WmCommentListVo;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.service.WmCommentService;
import com.heima.wemedia.service.WmUserService;
import com.jcraft.jsch.HASH;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author JianKang
 * @create 2023-11-06 15:06
 */
@Transactional
@Slf4j
@Service
public class WmCommentServiceImpl implements WmCommentService {
    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    WmUserService wmUserService;

    @Autowired
    ICommentClient commentClient;

    @Autowired
    MongoTemplate mongoTemplate;

    @Override
    public ResponseResult commentRepay(CommentRepaySaveDto dto) {
        if (dto == null || dto.getCommentId() == null || StringUtils.isBlank(dto.getContent())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        HashMap<String, Object> map = new HashMap<>();

        WmUser wmUser = wmUserService.getById(user.getId());
        log.info("---------------------User:{}", user);
        map.put("wmUser", JSON.toJSONString(wmUser));
        map.put("commentId", dto.getCommentId());
        map.put("content", dto.getContent());

        kafkaTemplate.send("comment-repay", JSON.toJSONString(map));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult like(CommentLikeDto dto) {

        if (dto == null || dto.getCommentId() == null || dto.getOperation() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmUser user = WmThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        HashMap<String, Object> map = new HashMap<>();

        WmUser wmUser = wmUserService.getById(user.getId());
        log.info("---------------------User:{}", user);
        map.put("wmUser", JSON.toJSONString(wmUser));
        map.put("dto", JSON.toJSONString(dto));


        kafkaTemplate.send("comment-like", JSON.toJSONString(map));

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Override
    public ResponseResult findCommentList(CommentListDto dto) {

        WmUser user = WmThreadLocalUtil.getUser();
        WmUser wmUser = wmUserService.getById(user.getId());
        log.info("---------------------User:{}", wmUser);

        Query query = Query.query(Criteria.where("entryId").is(dto.getArticleId()));
        Pageable pageable = PageRequest.of(dto.getPage() - 1, dto.getSize());
        query.with(pageable);
        query.with(Sort.by(Sort.Direction.DESC, "createdTime"));

        List<CommentRepayListVo> commentRepayListVoList = mongoTemplate.find(query, ApComment.class).stream().map(apComment -> {
            CommentRepayListVo commentRepayListVo = new CommentRepayListVo();
            CommentVo commentVo = new CommentVo();
            BeanUtils.copyProperties(apComment, commentVo);

            ApCommentLike apCommentLike = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(wmUser.getApUserId()).and("commentId").is(apComment.getId())), ApCommentLike.class);
            if (apCommentLike != null) {
                commentVo.setOperation((short) 0);
            } else {
                commentVo.setOperation((short) 1);
            }
            commentRepayListVo.setApComments(commentVo);

            Query query2 = Query.query(Criteria.where("commentId").is(apComment.getId())).with(Sort.by(Sort.Direction.DESC, "createdTime"));
            List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query2, ApCommentRepay.class);


            commentRepayListVo.setApCommentRepays(apCommentRepays);
            return commentRepayListVo;
        }).collect(Collectors.toList());

        log.info("----------------------commentRepayListVoList:{}", commentRepayListVoList);

        return ResponseResult.okResult(commentRepayListVoList);
    }
}
